package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.*;
import bean.Question;
import bean.Student;
public class AddStudent extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		doPost(req,res);
	}
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
	    int pageSize=10;
	    int showPage;
		StudentDao dao=new StudentDao();
		List<Student> all=dao.allStudent();
		int recordCount=all.size();
		int pageCount=(recordCount%pageSize==0)?(recordCount/pageSize):(recordCount/pageSize+1);
		String integer=req.getParameter("showPage");
		String sno=req.getParameter("sno");
	    if(sno!=null&&sno!=""){
	    	try{
	    		dao.deleteStudentBySno(sno);
			}
			catch(Exception ex){
				ex.printStackTrace();
			}
	    }
	    
		if(integer==null){
			String spwd=req.getParameter("spwd");
			String sname=req.getParameter("sname");
			String ssex=req.getParameter("ssex");
			String mailbox=req.getParameter("major");
			String grade=req.getParameter("grade");
			sno=new String(sno.getBytes("iso-8859-1"));
			spwd=new String(spwd.getBytes("iso-8859-1"));
			sname=new String(sname.getBytes("iso-8859-1"));
			ssex=new String(ssex.getBytes("iso-8859-1"));
			mailbox=new String(mailbox.getBytes("iso-8859-1"));
			grade=new String(grade.getBytes("iso-8859-1"));
			System.out.println(sno+spwd+sname+mailbox);
			try{
				for(int i=0;i<all.size();i++){
					Student s=all.get(i);
					if(!s.getSno().equalsIgnoreCase(sno)&&i==all.size()-1){
						Student stu=new Student(sno,sname,spwd,ssex,mailbox,grade);
						dao.addStudent(stu);
					}
				}
			}
			catch(Exception ex){
				ex.printStackTrace();
			}
			integer="1";
			  }
	    try{
	    	showPage=Integer.parseInt(integer);
	    }catch(NumberFormatException e){
	     showPage=1;
	    }
	    if(showPage<=1){
	     showPage=1;
	    }
	    if(showPage>=pageCount){
	     showPage=pageCount;
	    }
	   
	    if(showPage!=pageCount){
	    	int position=(showPage-1)*pageSize+1;
	    	ArrayList<Student> sl=dao.getOnePage(position, pageSize);
	    	req.setAttribute("stulist", sl);
	    }
	    else{
	    	int position=(showPage-1)*pageSize+1;
	    	ArrayList<Student> sl=dao.getLastPage(position);
	    	req.setAttribute("stulist", sl);
	    }
	    req.setAttribute("pageCount", pageCount);
	    req.setAttribute("showPage", showPage);
		req.getRequestDispatcher("stumanage.jsp").forward(req,res);
	}
}
